<template>
  <div class="file-upload-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>智能文件批量上传与检索</span>
      </div>
      <!-- 上传区域 -->
      <el-upload
        class="upload-demo"
        drag
        multiple
        :action="uploadUrl"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :file-list="fileList"
        :auto-upload="true"
        :data="uploadExtraData"
        :limit="20"
        :on-exceed="handleExceed"
        :show-file-list="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          支持批量上传 Word/PDF/图片/视频，单个文件不超过 100MB
        </div>
      </el-upload>
      <!-- 上传文件列表 -->
      <el-table
        v-if="uploadedFiles.length"
        :data="uploadedFiles"
        style="width: 100%; margin-top: 20px"
        size="small"
        border
      >
        <el-table-column prop="name" label="文件名" width="200" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
        <el-table-column prop="tags" label="标签">
          <template slot-scope="scope">
            <el-tag
              v-for="tag in scope.row.tags"
              :key="tag"
              size="mini"
              type="info"
              style="margin-right: 4px"
            >{{ tag }}</el-tag>
            <el-input
              v-if="scope.row.editingTag"
              v-model="scope.row.newTag"
              size="mini"
              style="width: 80px"
              @keyup.enter.native="addTag(scope.row)"
              @blur="scope.row.editingTag = false"
            />
            <el-button
              v-else
              icon="el-icon-plus"
              size="mini"
              @click="scope.row.editingTag = true"
              type="text"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="关键词" width="180">
          <template slot-scope="scope">
            <el-tag
              v-for="kw in scope.row.keywords"
              :key="kw"
              size="mini"
              type="success"
              style="margin-right: 4px"
            >{{ kw }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="摘要/预览" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="showPreview(scope.row)"
              type="primary"
              plain
            >预览</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 检索设置 -->
    <el-card style="margin-top: 30px">
      <div slot="header" class="clearfix">
        <span>检索设置</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="输入关键词" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="searchForm.tag" placeholder="选择标签" clearable>
            <el-option
              v-for="tag in allTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="选择类型" clearable>
            <el-option label="Word" value="word" />
            <el-option label="PDF" value="pdf" />
            <el-option label="图片" value="image" />
            <el-option label="视频" value="video" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">检索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 检索结果 -->
      <el-table
        v-if="searchResults.length"
        :data="searchResults"
        style="width: 100%; margin-top: 20px"
        size="small"
        border
      >
        <el-table-column prop="name" label="文件名" width="200" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
        <el-table-column prop="tags" label="标签">
          <template slot-scope="scope">
            <el-tag
              v-for="tag in scope.row.tags"
              :key="tag"
              size="mini"
              type="info"
              style="margin-right: 4px"
            >{{ tag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="相关性" width="100" />
        <el-table-column label="摘要/预览" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="showPreview(scope.row)"
              type="primary"
              plain
            >预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else style="margin-top: 20px; color: #888;">暂无检索结果</div>
    </el-card>

    <!-- 摘要/预览弹窗 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      width="50%"
      :title="previewFile.name + ' 摘要/预览'"
    >
      <div v-if="previewFile.type === 'image'">
        <img :src="previewFile.url" style="max-width: 100%" />
        <div style="margin-top: 10px; color: #666;">
          <strong>OCR识别结果：</strong>{{ previewFile.ocrText || '无' }}
        </div>
      </div>
      <div v-else-if="previewFile.type === 'video'">
        <video :src="previewFile.url" controls style="max-width: 100%" />
      </div>
      <div v-else>
        <div style="white-space: pre-wrap; color: #333;">
          <strong>摘要：</strong>{{ previewFile.summary || '无' }}
        </div>
        <div style="margin-top: 10px; color: #666;">
          <strong>关键词：</strong>
          <el-tag
            v-for="kw in previewFile.keywords"
            :key="kw"
            size="mini"
            type="success"
            style="margin-right: 4px"
          >{{ kw }}</el-tag>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'

export default {
  name: 'FileUploadSmart',
  data() {
    return {
      uploadUrl: '/api/upload', // 实际部署时替换为后端上传接口
      fileList: [],
      uploadedFiles: [],
      allTags: [],
      searchForm: {
        keyword: '',
        tag: '',
        type: ''
      },
      searchResults: [],
      previewDialogVisible: false,
      previewFile: {}
    }
  },
  computed: {
    uploadExtraData() {
      // 可扩展上传附加参数
      return {}
    }
  },
  methods: {
    beforeUpload(file) {
      // 限制类型和大小
      const isAllowed =
        file.type.includes('word') ||
        file.type.includes('pdf') ||
        file.type.startsWith('image/') ||
        file.type.startsWith('video/')
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isAllowed) {
        Message.error('仅支持 Word/PDF/图片/视频 文件')
        return false
      }
      if (!isLt100M) {
        Message.error('单个文件不能超过 100MB')
        return false
      }
      return true
    },
    handleUploadSuccess(response, file, fileList) {
      // 假设后端返回 { url, name, type, uploadTime }
      // 这里模拟后端智能处理返回
      const type = this.detectFileType(file)
      const now = new Date()
      const uploadTime = now.toLocaleString()
      const fileObj = {
        name: file.name,
        url: response.url || '',
        type,
        uploadTime,
        tags: [],
        editingTag: false,
        newTag: '',
        keywords: [],
        summary: '',
        ocrText: ''
      }
      // 模拟调用后端NLP/OCR
      this.processFileSmart(fileObj)
      this.uploadedFiles.push(fileObj)
      this.updateAllTags()
      Message.success('上传成功，正在智能分析...')
    },
    handleUploadError(err) {
      Message.error('上传失败')
    },
    handleExceed(files, fileList) {
      Message.warning('最多只能上传20个文件')
    },
    detectFileType(file) {
      const name = file.name.toLowerCase()
      if (name.endsWith('.doc') || name.endsWith('.docx')) return 'word'
      if (name.endsWith('.pdf')) return 'pdf'
      if (file.type.startsWith('image/')) return 'image'
      if (file.type.startsWith('video/')) return 'video'
      return 'other'
    },
    processFileSmart(fileObj) {
      // 实际应调用后端API，这里前端模拟
      if (fileObj.type === 'word' || fileObj.type === 'pdf') {
        // 模拟NLP
        setTimeout(() => {
          fileObj.keywords = this.mockExtractKeywords(fileObj.name)
          fileObj.summary = '这是文档的智能摘要（模拟）'
        }, 1000)
      } else if (fileObj.type === 'image') {
        // 模拟OCR
        setTimeout(() => {
          fileObj.ocrText = '图片中的文字内容（模拟）'
          fileObj.keywords = this.mockExtractKeywords(fileObj.ocrText)
        }, 1000)
      } else {
        // 视频等
        setTimeout(() => {
          fileObj.summary = '视频文件，暂无摘要'
        }, 500)
      }
    },
    mockExtractKeywords(text) {
      // 简单分词模拟
      return text
        .replace(/\.[^/.]+$/, '')
        .split(/[\s_\-]+/)
        .filter(Boolean)
        .slice(0, 5)
    },
    addTag(fileObj) {
      if (fileObj.newTag && !fileObj.tags.includes(fileObj.newTag)) {
        fileObj.tags.push(fileObj.newTag)
        this.updateAllTags()
      }
      fileObj.newTag = ''
      fileObj.editingTag = false
    },
    updateAllTags() {
      // 汇总所有标签
      const tagSet = new Set()
      this.uploadedFiles.forEach(f => f.tags.forEach(t => tagSet.add(t)))
      this.allTags = Array.from(tagSet)
    },
    handleSearch() {
      // 模拟检索，实际应调用后端
      let results = this.uploadedFiles.map(f => ({
        ...f,
        score: 0
      }))
      // 相关性打分
      results.forEach(f => {
        let score = 0
        if (
          this.searchForm.keyword &&
          ((f.summary && f.summary.includes(this.searchForm.keyword)) ||
            (f.ocrText && f.ocrText.includes(this.searchForm.keyword)) ||
            f.keywords.some(kw => kw.includes(this.searchForm.keyword)))
        ) {
          score += 10
        }
        if (
          this.searchForm.tag &&
          f.tags.includes(this.searchForm.tag)
        ) {
          score += 5
        }
        if (
          this.searchForm.type &&
          f.type === this.searchForm.type
        ) {
          score += 3
        }
        f.score = score
      })
      // 过滤无关项
      results = results.filter(f => f.score > 0)
      // 按相关性排序
      results.sort((a, b) => b.score - a.score)
      this.searchResults = results
    },
    resetSearch() {
      this.searchForm = {
        keyword: '',
        tag: '',
        type: ''
      }
      this.searchResults = []
    },
    showPreview(fileObj) {
      this.previewFile = fileObj
      this.previewDialogVisible = true
    }
  }
}
</script>

<style scoped>
.file-upload-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 0;
}
.upload-demo {
  width: 100%;
  margin-bottom: 20px;
}
.search-form {
  margin-bottom: 10px;
}
</style>
